import React, { useState } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  message,
  Popconfirm,
  Card,
  Space,
  Divider,
  DatePicker,
  Tag,
  Switch
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  DragOutlined
} from '@ant-design/icons';
import {
  deleteApi,
  selectListApi,
  sortApi
} from './services';
import dayjs from 'dayjs';
import { DndContext, DragEndEvent } from '@dnd-kit/core';
import { restrictToVerticalAxis } from '@dnd-kit/modifiers';
import { arrayMove, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { useTableRequest } from '@/hooks/useTableRequest';
import PageContent from '@/layout/pageContent';
import EditForm from './components/EditForm';
import SortRow from '@/components/DragTableRow';
import DragTable from '@/components/DragTable';

const { RangePicker } = DatePicker;

export interface Banner {
  id?: number;
  title: string;
  comment: string;
  status: number;
  linkUrl?: string;
  imageUrl: string;
  sortOrder?: number;
  createdAt?: string;
  updatedAt?: string;
}



const BannerList: React.FC = () => {
  const [sorting, setSorting] = useState(false);
  const [searchForm] = Form.useForm();
  const [handleModalInfo, setHandleModalInfo] = useState<{ visible: boolean, id?: number }>({
    visible: false
  });

  const {
    tableProps,
    refresh,
    setSearchParams,
    resetPagination,
    setDataSource
  } = useTableRequest<Banner>({
    url:"/banner/selectList",
    // immediate:false
  });

  const handleSearch = (values: any) => {
    const params = {
      ...values,
      ...(values.date ? {
        fromDate: values.date[0],
        toDate: values.date[1]
      } : {})
    };
    delete params.date;
    setSearchParams(params);
    resetPagination();
  };

  const handleResetSearch = () => {
    searchForm.resetFields();
    setSearchParams({});
    resetPagination();
  };

  const handleDelete = async (id: number) => {
    try {
      const res = await deleteApi(id);
      if (res.code === 200) {
        message.success('删除成功');
        refresh();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleDragEnd = ({ active, over }: DragEndEvent) => {
    console.log(active, over)
    if (active.id !== over?.id) {
      const dataSource = arrayMove(
        tableProps.dataSource,
        tableProps.dataSource.findIndex((i) => i.id === active.id),
        tableProps.dataSource.findIndex((i) => i.id === over?.id)
      );
      setDataSource(dataSource)
    }
  };

  const handleSort = async () => {
    setSorting(true);
    try {
      const res = await sortApi(tableProps.dataSource.map((item, index) => ({
        id: item.id,
        sortOrder: index + 1
      })));

      if (res.code === 200) {
        message.success('排序保存成功');
        refresh();
      }
    } catch (error) {
      message.error('排序保存失败');
    } finally {
      setSorting(false);
    }
  };


  const columns = [
    {
      title: '排序',
      key: 'sort',
      width: 70,
      render: () => <DragOutlined style={{ cursor: 'move' }} />,
    },
    {
      title: '名称',
      dataIndex: 'title',
      width: 120,
      sorter: true,

    },
    {
      title: '图片',
      dataIndex: 'imageUrl',
      width: 150,
      // render: (text: string) => (
      //   <img
      //     src={text}
      //     alt="banner"
      //     style={{ width: 100, height: 50, objectFit: 'cover' }}
      //   />
      // ),
    },
    {
      title: '链接',
      dataIndex: 'linkUrl',
      width: 150,
      render: (text: string) => (
        <a href={text} target="_blank" rel="noopener noreferrer">
          {text}
        </a>
      ),
    },
    {
      title: '描述',
      dataIndex: 'comment',
      width: 100,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 70,
      render: (status: number) => (
        <Tag color={status === 1 ? 'success' : 'error'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 150,
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: Banner) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            size="small"
            onClick={() => {
              setHandleModalInfo({
                visible: true,
                id: record.id
              })
            }}
          />
          <Popconfirm
            title="确定要删除这个Banner吗？"
            onConfirm={() => handleDelete(record.id!)}
          >
            <Button
              type="link"
              danger
              size="small"

              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <PageContent
      title="Banner设置"
      extra={
        <Space>
          <Button
            type="primary"
            loading={sorting}
            onClick={handleSort}
          >
            保存排序
          </Button>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setHandleModalInfo({
                visible: true
              })
            }}
          >
            新建Banner
          </Button>
        </Space>
      }
    >
      {/* 搜索表单 */}
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="title" label="名称">
          <Input placeholder="请输入Banner名称" />
        </Form.Item>
        <Form.Item name="date" label="日期范围">
          <RangePicker />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button
              type="primary"
              htmlType="submit"
              icon={<SearchOutlined />}
            >
              搜索
            </Button>
            <Button onClick={handleResetSearch}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <DragTable
        // rowKey="id"
        
        columns={columns}
        {...tableProps}
        scroll={{ x: 1000 }}
        handleDragEnd={handleDragEnd}
      />

      <EditForm
        id={handleModalInfo.id}
        onCancel={() => { setHandleModalInfo({ visible: false }) }}
        modalVisible={handleModalInfo.visible}
        onSuccess={() => { refresh() }}
      />
    </PageContent>
  );
};

export default BannerList;